package cn.zyx.common.utils.sys.log;

import cn.zyx.common.enums.LogType;
import cn.zyx.common.properites.CacheProperties;
import cn.zyx.common.utils.cache.ehcache.CacheUtils;
import cn.zyx.common.utils.sys.SpringContextHolderUtils;
import cn.zyx.common.utils.sys.UserUtils;
import cn.zyx.sys.entity.Log;
import cn.zyx.sys.entity.Menu;
import cn.zyx.sys.entity.User;
import cn.zyx.sys.mapper.LogMapper;
import cn.zyx.sys.mapper.MenuMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import static org.apache.commons.lang3.StringUtils.isNotBlank;


public class LogUtils {

    /**
     * 保存日志
     */
    public static void saveLog(HttpServletRequest request, String title, String type){
        saveLog(request, null, null, title, type);
    }

    /**
     * 保存日志
     * @param ex
     * 异常信息
     * @param title
     * 日志名称
     * @param type
     * 日志类型
     */
    public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title, String type){
        User user = UserUtils.getUser();
        if (user != null && user.getId() != null){
            Log log = new Log();
            log.setTitle(title);
            if(StringUtils.isBlank(type)){
                log.setType(ex == null ? LogType.ACCESS.getType() : LogType.EXCEPTION.getType());
            }else {
                log.setType(type);
            }
            log.setRemoteAddr(getRemoteAddr(request));
            log.setUserAgent(request.getHeader("user-agent"));
            log.setRequestUri(request.getRequestURI());
            log.setParams(request.getParameterMap());
            log.setMethod(request.getMethod());
            // 异步保存日志
            new SaveLogThread(log, handler, ex).start();
        }
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request){
        String remoteAddr = request.getHeader("X-Real-IP");
        if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        }else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        }else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }



}
